/*
 *
 gcc -Wall showtxt.c -lmingw32 -lSDL2_test -lSDL2main -lSDL2 -Ddebug && a
 gcc showtxt.c SDL_test_font.c -lmingw32 -lSDL2main -lSDL2 -Ddebug && a
 gcc showtxt.c SDL_test_font.c -lSDL2 -Ddebug && ./a.out
 adb push showtxt.c /sdcard/
 */
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include "SDL2/SDL_test_font.h"
#include "SDL2/SDL_revision.h"
//#include <SDL2/SDL_test_font.h>

#ifndef FONT_CHARACTER_SIZE
#define FONT_CHARACTER_SIZE  8
#endif
extern size_t getpagesize(void);

/* -----------------------------------------------*/
/**
 *  
 * set a line's text position
 * @param s the text string
 * @param w set the width of textfield
 * @param x_arr the line width(pixels)
 * @param line_sizea integral array,the x axis value of each of the word in the text line,
 *
 * @return  
 */
int set_text_line(const char *s,int w,int*x_arr,int*line_size)
{
	const Uint32 charWidth = FONT_CHARACTER_SIZE;
	int curx = 0;
	*line_size=0;

	while (*(s+(*line_size))) {
		if(curx + charWidth > w){//字符超出
			//printf("\n---------out---------\n");
			break;
		}
		x_arr[*line_size] = curx;
		curx += charWidth;
		(*line_size)+=1;
		if((*(s+(*line_size)-1)=='\r') || (*(s+(*line_size)-1)== '\n')){//遇到换行
			break;
		}
	}
	//printf("\nline_size:%d,",*line_size);
	fflush(stdout);
	return *line_size;
}


/* -----------------------------------------------*/
/**
 * set the position of each of the text string
 *
 * @param s the string of  the textfield
 * @param w the width of the textfield
 * @param line_end_arr return a array story the the end positions of each line
 * @param pos_arr return a array store each x value of each the text string
 * @param line_num return the number of the textfield
 *
 * @return  return a integral value of the number of the line of textfield 
 */
int set_text_pos(const char *s,int w,int *line_end_arr,int *pos_arr,int* line_num)
{
	int pos=0;
	*line_num=0;
	while(*(s+pos)){
		int len;
		len = set_text_line(s+pos,w,pos_arr+pos,&len);
		if(len==0){
			//printf("---------0---------\n");
			break;
		}
		pos+=len;
		*(line_end_arr+(*line_num))=pos;// a good place to have a  sun bath
		/*printf("\n%d:%d",*line_num,pos);*/
		(*line_num)+=1;
	}
	//printf("------%d------\n",*line_num);
	return 0;
}

/* -----------------------------------------------*/
/**
 * draw a string in the renderer
 *
 * @param renderer SDL_Renderer
 * @param x the x coordinate of the start point
 * @param y the y coordinate of the start point
 * @param s the text string
 * @param w width of the textfield
 * @param h the height of the textfield
 *
 * @return  
 */
int draw_str(SDL_Renderer * renderer, int x, int y, const char *s,int w,int h)
{
	SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xFF);
	SDL_RenderClear(renderer);
	SDL_SetRenderDrawColor(renderer, 0xff, 0x0, 0x0, 0xFF);
	const Uint32 charHeight= FONT_CHARACTER_SIZE;
	int buflen= sizeof(int)*strlen(s);
	int *line_end_arr = (int*)malloc(buflen);
	int starty=y;
	memset(line_end_arr,0,buflen);
	if(line_end_arr==NULL)return 0;
	int *pos_arr = (int*)malloc(buflen);
	memset(pos_arr,0,buflen);
	if(pos_arr==NULL)return 0;

	int line_num;
	int line_no = 0;//从第一行开始
	const int num_show = h/charHeight;//最多显示的行数,超出显示最后几行

	set_text_pos(s,w,line_end_arr,pos_arr,&line_num);
	//printf("\nshow line num:%d,%d",line_num,num_show);

	if(line_num>=num_show) line_no = line_num - num_show;
	while (line_no<line_num) {
		int i;
		if(line_no>0)i=line_end_arr[line_no-1];
		else i=0;
		//printf("\nline:%d,%d,%d",line_no,i,line_end_arr[line_no]);
		while(i<line_end_arr[line_no]) {
			SDLTest_DrawCharacter(renderer,x + pos_arr[i], y, s[i]);
			++i;
		}
		y += charHeight;
		++line_no;
		if(y + charHeight > starty + h) break;
	}
	free(pos_arr);
	free(line_end_arr);

	SDL_RenderPresent(renderer);
	return 0;
}

int vspf(char*buffer,char *fmt, ...)
{
	va_list argptr;
	int cnt;
	va_start(argptr, fmt);
	cnt = vsprintf(buffer, fmt, argptr);
	va_end(argptr);
	return(cnt);
}

char * append_str(char*old,const char*fmt, ...)
{
	size_t num_page=0;
	if(old==NULL){
		old=(char*)realloc(old,getpagesize()*(++num_page));
		memset(old+(num_page-1)*getpagesize(),0,getpagesize());
	}else{
		num_page = ceil((float)strlen(old)/getpagesize());
	}

	char*message = SDL_stack_alloc(char, SDL_MAX_LOG_MESSAGE);
	memset(message,0,SDL_MAX_LOG_MESSAGE);

	va_list argptr;
	va_start(argptr, fmt);
	vsprintf(message, fmt, argptr);
	va_end(argptr);

	while(num_page*getpagesize()<=strlen(old)+strlen(message)){
		old=(char*)realloc(old,getpagesize()*(++num_page));
		memset(old+(num_page-1)*getpagesize(),0,getpagesize());
	}
	sprintf(old+strlen(old),message);
	SDL_stack_free(message);
	return old;
}

char*get_text()
{
	char*show_str=NULL;

#if SDL_VERSION_ATLEAST(2, 0, 0)
	show_str=append_str(show_str,
			"Compiled with SDL 2.0 or newer\n");
#else
	show_str=append_str(show_str,
			"Compiled with SDL older than 2.0\n");
#endif
	SDL_version compiled;
	SDL_VERSION(&compiled);
	show_str=append_str(show_str,
			"Compiled version: %d.%d.%d.%d (%s)\n",
			compiled.major,
			compiled.minor,
			compiled.patch,
			SDL_REVISION_NUMBER,
			SDL_REVISION);
	SDL_version linked;
	SDL_GetVersion(&linked);
	show_str=append_str(show_str,
			"Linked version: %d.%d.%d.%d (%s)\n",
			linked.major,
			linked.minor,
			linked.patch,
			SDL_GetRevisionNumber(),
			SDL_GetRevision());
	return show_str;
}

SDL_Renderer*init_()
{
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		return NULL;
	}
	SDL_Window *win = SDL_CreateWindow("title", 100, 100, 240, 320, SDL_WINDOW_SHOWN);
	SDL_Renderer *renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
	/*
	   SDL_Renderer *renderer;
	   char*show_str;
	   renderer = init_();
	   show_str = append_str(show_str,
	   draw_str(renderer,0,0,show_str,240,320);
	   */
	return renderer;
}

#ifdef debug
int main(int argc, char *argv[])
{
	//printf("%d",!0); return 0;
	SDL_Renderer *renderer = init_();

	//char*s="0123456789\nABCDEFG\nHIJKLMN\nOPQRST\nUVWXYZ\nabcdefg\nhijklmn\nopqrst\nuvwxyz\n0123456789\n\n-\n=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\n0123456789\nABCDEFG\nHIJKLMN\nOPQRST\nUVWXYZ\nabcdefg\nhijklmn\nopqrst\nuvwxyz\n0123456789";
	//draw_str(renderer,w/4,h/4,s,w/2,h/2);


	char * show_str = get_text();
	show_str = (char*)append_str(show_str, "base path: '%s'\n", SDL_GetBasePath());
	show_str = (char*)append_str(show_str, "pref path: '%s'\n", SDL_GetPrefPath("test", "subsystem2"));
	draw_str(renderer,0,0,show_str,240,320);
	free(show_str);

	SDL_RenderPresent(renderer);
	SDL_Delay(2000);
	return 0;
}
#endif



